<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model.trim="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="search" />
        <!-- 树形组件 -->
        <el-tree ref="tree" node-key="id" :data="dptData" :props="defaultProps" :expand-on-click-node="false" :default-expand-all="true" highlight-current @current-change="nodeChange" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'addEmployee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="roleList">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.slice(0, 1) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template #default="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail?id=${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :page-size="queryParams.pagesize"
            :current-page="queryParams.page"
            @current-change="sizeChange"
          />
        </el-row>
      </div>
    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <!-- 分配角色弹层 -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <!-- 弹层内容 -->
      <!-- checkbox -->
      <el-checkbox-group v-model="partIds">
        <el-checkbox v-for="item in partList" :key="item.id" :label="item.id" style="margin-bottom: 10px;">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentListApi } from '@/api/department'
import { assignRoleApi, deleteEmployeeApi, exportEmployeeExcelApi, getEmployeeDetailApi, getEmployeeListApi, getRoleListApi } from '@/api/employee'
import { transListToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import ImportExcel from './components/ImportExcel.vue'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      dptData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      queryParams: {
        page: 1,
        pagesize: 10,
        keyword: '',
        departmentId: null
      },
      total: 0,
      roleList: [],
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      showRoleDialog: false, // 控制分配角色弹层的显示和隐藏
      partList: [], // 角色弹层的展示列表
      partIds: [], // 用来双向绑定checkBoxGroup数据的
      currentUserId: '' // 当前点击的角色分配的员工id
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    async getDepartmentList() {
      const res = await getDepartmentListApi()
      // 调用递归函数将响应数据转化为树形结构
      this.dptData = transListToTreeData(res, 0)
      // 保存第一个结点的id
      this.queryParams.departmentId = this.dptData[0].id
      // 通过 key 设置某个节点的当前选中状态
      this.$nextTick(() => {
        // 视图更新后执行
        // 设置默认选中第一个节点
        this.$refs.tree.setCurrentKey(this.dptData[0].id)
      })
      // 只有保存了第一个结点的id，才能获取到员工列表
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const { total, rows } = await getEmployeeListApi(this.queryParams)
      this.total = total
      this.roleList = rows
    },
    // 点击节点切换部门
    nodeChange(node) {
      // console.log(node)
      // 记录当前结点的id
      this.queryParams.departmentId = node.id
      // 切换部门要重置结点的页码
      this.queryParams.page = 1
      // 重新获取员工列表
      this.getEmployeeList()
    },
    // 切换页码
    sizeChange(page) {
      this.queryParams.page = page
      this.getEmployeeList()
    },
    // 关键字搜索
    search() {
      // 利用定时器防抖处理
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    },
    // excel导出
    async exportExcel() {
      const res = await exportEmployeeExcelApi()
      // console.log(res)
      // 使用一个npm包 直接将blob文件下载到本地 file-saver
      // FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    // 删除员工信息
    async confirmDel(id) {
      await deleteEmployeeApi(id)
      // 如果当前页仅剩一条数据，且当前页不为第一页时，需要跳转到上一页，再重新请求数据
      if (this.roleList.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
      // 提示删除成功消息
      this.$message.success('删除成功')
    },
    // 点击角色按钮弹出层
    async btnRole(id) {
      this.currentUserId = id
      this.partList = await getRoleListApi()
      const { roleIds } = await getEmployeeDetailApi(id)
      this.partIds = roleIds
      this.showRoleDialog = true
    },
    // 点击角色的确定
    async  btnRoleOK() {
      await assignRoleApi({
        id: this.currentUserId,
        roleIds: this.partIds
      })
      this.$message.success('分配用户角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
